// pages/order/ordering/ordering.js
var http = require('../../../utils/server.js');
var util = require('../../../utils/util.js')
Page({
  data: {
    express: ['普通快递', '顺丰'],
    expressIndex: 0,
    addressList: [{
      number: 1
    }],
    selectAddress: [],
    isSelectedAddress: false,
    replaceOrder: false,
    remark: "",
    specifications: [],
    gangPrice: [],
    productList: [],
    totalNumber: 1,
    numbers: [1],
    showDialog: false,
    postage: 0.0,
    totalPrice: 0.0,
    numberDisabled: [],
  },
  onLoad: function(option) {
    console.log('下单页面收到参数', option)
    var that = this
    if (option.replaceOrder == '1')
      that.setData({
        replaceOrder: true
      })
    if (option.hasOwnProperty('shop_id')) {
      if (option.shop_id) {
        that.setData({
          shop_id: option.shop_id,
          replaceOrder: false
        })
      }
    }
    if (option.specifications)
      that.setData({
        specifications: option.specifications.split(",")
      })
    if (option.product_ids)
      that.setData({
        product_ids: option.product_ids.split(",")
      })
    if (option.numbers)
      that.setData({
        numbers: option.numbers.split(",")
      })
    if (that.data.replaceOrder) {
      //获取寄件人信息
      http.post({
        url: "address/getSendAddress"
      }, function(data) {
        console.log('寄件信息', data)
        if (data) {
          that.setData({
            senderName: data.consignor,
            senderPhone: data.phone
          })
        }
      })
    }
    http.post({
      url: "product/getDetails",
      product_ids: that.data.product_ids,
      shop_id: that.data.shop_id
    }, function(data) {
      console.log('商品详情', data)
      var totalPrice = 0
      var gangPrice = []
      for (dsi in that.data.specifications) {
        console.log(data[dsi].specifications)
        for (si in data[dsi].specifications) {
          var s = data[dsi].specifications[si]
          if (s.title == that.data.specifications[dsi]) {
            data[dsi].gang_price = s.gang_price
            gangPrice[dsi] = s.gang_price
            totalPrice += s.gang_price * that.data.numbers[dsi]
          }
        }
      }
      totalPrice = Math.round(totalPrice * 100) / 100
      console.log('totalPrice', totalPrice)
      that.data.gangPrice = gangPrice
      that.setData({
        productList: data,
        totalPrice: totalPrice
      })
    })


  },
  onShow: function() {

  },
  bindPickerChange: function(e) {
    this.setData({
      expressIndex: e.detail.value
    })
    this.calcTotalNumber()
  },
  deleteAddress: function(e) {
    var index = e.currentTarget.dataset.index
    var addressList = this.data.addressList
    addressList.splice(index, 1)
    this.setData({
      addressList: addressList
    })
  },
  sub: function(e) {
    var index = e.currentTarget.dataset.index
    var n = this.data.numbers
    var nd = this.data.numberDisabled
    n[index]--
      if (n[index] <= 1) {
        n[index] = 1
        nd[index] = {
          disabled: true
        }
      }
    this.setData({
      numbers: n,
      numberDisabled: nd
    })

    this.calcTotalNumber()
  },
  add: function(e) {
    var index = e.currentTarget.dataset.index
    var n = this.data.numbers
    var nd = this.data.numberDisabled
    n[index]++
      nd[index] = {
        disabled: false
      }
    this.setData({
      numbers: n,
      numberDisabled: nd
    })

    this.calcTotalNumber()
  },
  calcTotalNumber: function() {
    var that = this;
    var totalPrice = 0
    var t = 0
    var al = this.data.addressList
    var n = this.data.numbers
    var g = this.data.gangPrice
    for (x in al) {
      var currentNum = 0
      var currentAT = 0
      for (y in n) {
        currentNum += al[x].number * n[y]
        currentAT += al[x].number * n[y] * g[y]
      }
      t += currentNum
      totalPrice += currentAT
    }

    totalPrice = Math.round(currentAT * 100) / 100
    this.setData({
      totalNumber: t,
      totalPrice: totalPrice
    })
    if (that.data.expressIndex == 1) {
      var postage = 0
      var addressList = that.data.addressList;
      for (var i in addressList) {
        if (!addressList[i].province)
          return util.showError('请选择收货地址')
        var ids = []
        var tn = []
        for (var j in that.data.productList) {
          var idsIndex = ids.indexOf(that.data.productList[j].id)
          if (idsIndex == -1) {
            ids.push(that.data.productList[j].id)
            tn.push(parseInt(that.data.numbers[j]))
          } else {
            tn[idsIndex] += parseInt(that.data.numbers[j])
          }
        }

        for (var j in ids) {
          http.post({
            url: "order/countPostage",
            product_id: ids[j],
            province: addressList[i].province,
            number: tn[j], // 当前版本 是单商品
          }, function(data) {
            var p = Math.round(data.data * 100) / 100
            postage += p
            totalPrice += p
            that.setData({
              postage: postage,
              totalPrice: Math.round(totalPrice * 100) / 100
            })

          })
        }

      }
    }

  },

  addAddress: function() {
    wx.navigateTo({
      url: '/pages/address/chooseAddress/chooseAddress'
    })
  },
  bindRemark: function(e) {
    this.setData({
      remark: e.detail.value
    })
  },
  bindSenderName: function(e) {
    this.setData({
      senderName: e.detail.value
    })
  },
  bindSenderPhone: function(e) {
    this.setData({
      senderPhone: e.detail.value
    })
  },
  toggleDialog: function(e) {
    this.setData({
      showDialog: !this.data.showDialog,
    })
  },
  createOrder: function() {
    var postData = {}
    if (this.data.replaceOrder) {
      postData = {
        url: "order/replaceOrder",
        product_id: this.data.product_ids[0],
        express: this.data.express[this.data.expressIndex],
        remark: this.data.remark,
        specifications: this.data.specifications[0],
        sender_phone: this.data.senderPhone,
        sender_name: this.data.senderName,
        total_number: this.data.totalNumber
      }
    } else {
      postData = {
        url: "order/create",
        product_ids: this.data.product_ids,
        shop_id: this.data.shop_id,
        express: this.data.express[this.data.expressIndex],
        remark: this.data.remark,
        specifications: this.data.specifications,
        numbers: this.data.numbers,
      }
    }
    postData.address = []
    for (a of this.data.addressList) {
      console.log(a)
      postData.address.push({
        address_id: a.id,
        number: a.number
      })
    }
    http.post(postData, function(data) {
      console.log('下单', data)
      wx.requestPayment({
        'timeStamp': data.timeStamp,
        'nonceStr': data.nonceStr,
        'package': data.package,
        'signType': data.signType,
        'paySign': data.paySign,
        'success': function(e) {
          console.log("支付成功！", e)
          util.showSuccess('支付成功！')
          wx.redirectTo({
            url: "/pages/order/paySuccess/paySuccess?order_id=" + data.order_id + '&money=' + data.recharge
          })
        },
        'fail': function(e) {
          console.log("支付失败！", e)
          util.showError('支付失败！')
        }
      })
    })
  },
  chooseAddress: function(e) {
    console.log('父级选择地址参数', e)
    var that = this
    var selectAddress = e
    if (selectAddress) {
      http.post({
        url: "address/getAll"
      }, function(data) {
        var allAddressList = []
        for (d in data) {
          allAddressList.push(data[d])
        }
        console.log('allAddressList', allAddressList)
        that.setData({
          isSelectedAddress: false,
          allAddressList: allAddressList
        })
        var allAddressList = that.data.allAddressList
        var addressList = []
        for (d in allAddressList) {
          if (selectAddress.indexOf(allAddressList[d].id) > -1) {
            allAddressList[d].number = 1
            allAddressList[d].disabled = true
            addressList.push(allAddressList[d])
          }
        }
        console.log('选择的地址', addressList)
        that.setData({
          isSelectedAddress: true,
          addressList: addressList
        })
        that.calcTotalNumber()

      })
    }
  },

})